// 215
package org.hwadee.controller;

import cn.hutool.http.HtmlUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.hwadee.dto.JsonResult;
import org.hwadee.entity.Comment;
import org.hwadee.entity.Post;
import org.hwadee.entity.Result;
import org.hwadee.entity.User;
import org.hwadee.service.CommentService;
import org.hwadee.service.PostService;
import org.hwadee.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Controller
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    CommentService commentService;

    @Autowired
    PostService postService;

    @Autowired
    UserService userService;

    @RequestMapping(value = "/insertComment", method = {RequestMethod.POST})
    public JsonResult insertComment(HttpServletRequest request, Comment comment, HttpSession session) throws ParseException {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return new JsonResult().fail("请先登录");
        }
        Post post = postService.getPostByIdAndStatus(comment.getCommentPostId(), 1);
        if (post == null) {
            return new JsonResult().fail("帖子不存在");
        }
        comment.setCommentUserId(user.getUserId());
        comment.setCommentCreateTime(new Date());
        comment.setCommentAuthorName(user.getNickname());
        comment.setCommentContent(HtmlUtil.escape(comment.getCommentContent()));
        try {
            commentService.insertComment(comment);
            //更新帖子的评论数
            postService.updateCommentCount(post.getPostId());
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult().fail();
        }
        return new JsonResult().ok();
    }

    /**
     * 评论页面
     * 我发送的评论
     *
     * @param page     页码
     * @param pageSize 页大小
     * @param session  session
     * @param model    model
     * @return 评论页面
     */
    @RequestMapping(value = "/myCommentList")
    public String myCommentList(@RequestParam(value = "page", defaultValue = "1") int page,
                                @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
                                Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        PageHelper.startPage(page, pageSize);
        List<Comment> comments;
        if (user.getState() == 0) {
            comments = commentService.getCommentsByCommentUserId(user.getUserId());
        } else {
            comments = commentService.getAllComments();
        }
        PageInfo<Comment> pageInfo = new PageInfo<Comment>(comments);
        model.addAttribute("comments", comments);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("pageUrlPrefix", "/admin/comment?page");
        return "myCommentList";
    }

    /**
     * 评论页面
     * 我收到的评论
     *
     * @param page     页码
     * @param pageSize 页大小
     * @param session  session
     * @param model    model
     * @return 评论页面
     */
    @RequestMapping(value = "/receiveCommentList")
    public String myReceiveComment(@RequestParam(value = "page", defaultValue = "1") int page,
                                   @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
                                   Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        PageHelper.startPage(page, pageSize);
        List<Comment> comments = commentService.getReceiveCommentByUserId(user.getUserId());
        PageInfo<Comment> pageInfo = new PageInfo<Comment>(comments);
        model.addAttribute("comments", comments);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("pageUrlPrefix", "/admin/comment?page");
        return "myCommentList";
    }

    /**
     * 删除评论
     *
     * @param id      批量ID
     * @param session session
     */
    @RequestMapping(value = "/delete/{id}")
    public void deleteComment(@PathVariable("id") Integer id, HttpSession session) {
        Comment comment = commentService.getCommentByCommentId(id);
        User user = (User) session.getAttribute("user");
        // 如果不是管理员，访问其他用户的数据，没有权限
        if (user.getState() != 1 && !Objects.equals(comment.getCommentUserId(), user.getUserId())) {
            return;
        }
        //删除评论
        commentService.deleteCommentByCommentId(id);
        //删除其子评论
        List<Comment> childCommentList = commentService.listChildComment(id);
        for (int i = 0; i < childCommentList.size(); i++) {
            commentService.deleteCommentByCommentId(childCommentList.get(i).getCommentId());
        }
        //更新文章的评论数
        Post post = postService.getPostByIdAndStatus(comment.getCommentPostId(), 1);
        postService.updateCommentCount(post.getPostId());
    }

    /**
     * 编辑评论页面显示
     *
     * @param id      评论id
     * @param model   model
     * @param session session
     * @return 评论编辑页面
     */
    @RequestMapping(value = "/edit/{id}")
    public String editCommentView(@PathVariable("id") Integer id, Model model, HttpSession session) {
        // 没有权限操作,只有管理员可以操作
        User user = (User) session.getAttribute("user");
        if (user.getState() != 1) {
            return "redirect:/403";
        }
        Comment comment = commentService.getCommentByCommentId(id);
        model.addAttribute("comment", comment);
        return "Admin/Comment/edit";
    }

    /**
     * 编辑评论提交
     *
     * @param comment 评论
     * @param session session
     * @return 评论页面
     */
    @RequestMapping(value = "/editSubmit", method = RequestMethod.POST)
    public String editCommentSubmit(Comment comment, HttpSession session) {
        User user = (User) session.getAttribute("user");
        // 没有权限操作,只有管理员可以操作
        if (user.getState() != 1) {
            return "redirect:/403";
        }
        commentService.updateComment(comment);
        return "redirect:/admin/comment";
    }

    /**
     * 回复评论页面显示
     *
     * @param id    评论id
     * @param model model
     * @return 评论回复页面
     */
    @RequestMapping(value = "/reply/{id}")
    public String replyCommentView(@PathVariable("id") Integer id, Model model) {
        Comment comment = commentService.getCommentByCommentId(id);
        model.addAttribute("comment", comment);
        return "Admin/Post/postDetail";
    }

    @RequestMapping(value = "/replySubmit", method = RequestMethod.POST)
    public Result replyCommentSubmit(@RequestParam(value = "commentPid", defaultValue="-1") int commentPid,
                                     @RequestParam(value = "commentPostId", defaultValue="-1") int commentPostId,
                                     @RequestParam(value = "commentContent") String commentContent,
                                     HttpSession session, Model model) throws ParseException {
        if(session.getAttribute("user")==null) {
            return new Result(404);
        }
        if(commentPostId==-1) {
            return new Result(404);
        }
        Post post = postService.getPostByIdAndStatus(commentPostId,1);
        User user = (User)session.getAttribute("user");
        if(post == null) {
            return new Result(404);
        }
        Comment comment = new Comment();
        comment.setCommentUserId(user.getUserId());
        comment.setCommentPostId(commentPostId);
        comment.setCommentContent(commentContent);
        comment.setCommentStatus(1);
        comment.setCommentCreateTime(new Date());
        if(commentPid >0) {
            comment.setCommentPid(commentPid);
        }
        commentService.insertComment(comment);
        postService.updateCommentCount(post.getPostId());
        return new Result(200);
    }

}
